package com.tm.hutool.aop;


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Aspect
@Component
@Slf4j
public class TestAspcet {

    /**
     * 前置通知
     * 后置通知
     * 环绕通知
     * 抛出异常通知
     * 返回通知
     *
     *@Pointcut("execution(public void com.example.junitspringboot.service.HelloService.sayHi(..))")
     */
    @Pointcut("execution(public * com.tm.hutool.controller..*Controller.*(..))")
    public void pointCut(){}

//    @Before("pointCut()")
//    public void before(){
//        System.out.println("前置通知");
//    }


    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint){
        long currentTimeMillis = System.currentTimeMillis();
        System.out.println("环绕通知开始");
        log.info("====================请求开始=============================");
        //获取requestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //获取request上下文
        HttpServletRequest request =(HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        String requestURI = request.getRequestURI();
        log.info("请求路径={}",requestURI);
        log.info("请求的ip={}",request.getRemoteHost());
        Map<String, String[]> parameterMap = request.getParameterMap();
        String jsonString = JSONObject.toJSONString(parameterMap);
        log.info("请求参数：{}",jsonString);
        log.info("请求类型：{}",request.getMethod());
        Signature signature = joinPoint.getSignature();
        Object proceed = null;
        try {
            proceed = joinPoint.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        log.info("返回信息：{}",proceed==null?null:JSONObject.toJSONString(proceed));
        long endTime = System.currentTimeMillis();
        log.info("====================请求结束=========耗时={} =============",endTime-currentTimeMillis);
        return proceed;
    }

//    @After("pointCut()")
//    public void after(){
//        System.out.println("后置通知");
//    }
//
//    @AfterReturning("pointCut()")
//    public void returning(){
//        System.out.println("返回通知");
//    }
//
//    @AfterThrowing("pointCut()")
//    public void afterThrowing(){
//        System.out.println("异常通知");
//    }
}
